<div id="innerContainer">
    <div class="row">
        <div class="form-body">
            <form id="mapBasicForm">
                <div class="form-title" data-trans="port_map"></div>
                <div class="content">
                    <div class="row-fluid">
                        <label class="span4 side-right" data-trans="port_map_setting"></label>
                        <div class="span8">
                            <div class="row">
                                <div class="col-xs-4">
                                    <input type="radio" name="mapGrp" id="mapEnable" data-bind="checked: portMapEnable" value="1" />
                                    <label for="mapEnable" data-trans="enable"></label>

                                    <input type="radio" name="mapGrp" id="mapDisable" data-bind="checked: portMapEnable" value="0" />
                                    <label for="mapDisable" data-trans="disable"></label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-buttons">
                    <input type="submit" class="btn-1 btn-primary" data-trans="apply" />
                </div>
                <div class="form-note">
                    <div class="notes-title">&nbsp;</div>
                    <ul class="notes-content">
                        <li data-trans="port_map_note_info"></li>
                    </ul>
                </div>
            </form>
            <div data-bind="visible: oriPortMapEnable() == '1' && portMapEnable() == '1' ">
                <form id="portMapForm">
                    <div class="form-title">
                        <div data-trans="port_map_setting"></div>
                    </div>
                    <div class="content">
                        <div class="row-fluid">
                            <div class="span4 side-right">
                                <label for="txtSourcePort" data-trans="source_port"></label>
                                <i class="colorRed">*</i>
                            </div>

                            <div class="span8">
                                <input type="text" name="txtSourcePort" id="txtSourcePort" data-bind="value: sourcePort" class="required form-control" maxlength="5" />

                                <label id="sourcePortExamLabel">(1~65000)</label>
                                <div id="txtSourcePortErrorDiv"></div>
                            </div>
                        </div>
                        <div class="row-fluid">
                            <div class="span4 side-right">
                                <label for="txtDestIpAddress" data-trans="dest_ip_address"></label>
                                <i class="colorRed">*</i>
                            </div>

                            <div class="span8">
                                <input type="text" name="txtDestIpAddress" id="txtDestIpAddress" data-bind="value: destIpAddress" class="required form-control" maxlength="15" />

                                <label data-trans="ipExam" id="ipExamLabel"></label>
                                <div id="txtDestIpAddressErrorDiv"></div>
                            </div>
                        </div>
                        <div class="row-fluid">
                            <div class="span4 side-right">
                                <label for="txtDestPort" data-trans="dest_port"></label>
                                <i class="colorRed">*</i>
                            </div>

                            <div class="span8">
                                <input type="text" name="txtDestPort" id="txtDestPort" data-bind="value: destPort" class="required form-control" maxlength="5" />

                                <label id="destPortExamLabel">(1~65000)</label>
                                <div id="txtDestPortErrorDiv"></div>
                            </div>
                        </div>
                        <div class="row-fluid">
                            <label class="span4 side-right" for="protocol" data-trans="protocol"></label>
                            <div class="span8">
                                <select id="protocol" data-transid="protocol" data-bind="options: modes, value: selectedMode, optionsText: transOption('protocol'), optionsValue: 'value'" class="form-control"></select>
                            </div>
                        </div>
                        <div class="row-fluid">
                            <div class="span4 side-right">
                                <label for="txtComment" data-trans="comment"></label>
                                <i class="colorRed">*</i>
                            </div>

                            <div class="span8">
                                <input type="text" name="txtComment" id="txtComment" data-bind="value: comment" class="required form-control" maxlength="32" />
                            </div>
                        </div>
                    </div>
                    <div class="form-buttons">
                        <input type="submit" class="btn-1 btn-primary" data-trans="apply" />
                    </div>
                    <div class="form-note">
                        <div class="notes-title">&nbsp;</div>
                        <ul class="notes-content">
                            <li data-trans="port_map_note_port"></li>
                            <li data-trans="port_map_note_dest_ip_address"></li>
                            <li data-trans="port_map_note_protocol"></li>
                            <li data-trans="port_map_note_comment"></li>
                            <li data-trans="rule_max_note"></li>
                        </ul>
                    </div>
                </form>
                <form id="portMapListForm">
                    <div class="form-title">
                        <div data-trans="port_map_list"></div>
                    </div>
                    <div class="content">
                        <div id="portMaps" class="fixTableScroll" data-bind="simpleGrid: gridTemplate"></div>
                    </div>
                    <div class="form-buttons">
                        <input type="submit" class="btn-1 btn-primary" data-trans="delete" data-bind="enable: gridTemplate.checkedCount() > 0" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $(function() {
        var service = window._service;
        var config = service.config;

        var protocolModes = _.map(config.MAP_PROTOCOL_MODES, function(item) {
            return new Option(item.name, item.value);
        });

        var columnsTmpl = [{
            columnType: "checkbox",
            rowText: "index",
            width: "8%"
        }, {
            headerTextTrans: "source_port",
            rowText: "sourcePort",
            width: "20%"
        }, {
            headerTextTrans: "dest_ip_address",
            rowText: "destIpAddress",
            width: "20%"
        }, {
            headerTextTrans: "dest_port",
            rowText: "destPort",
            width: "20%"
        }, {
            headerTextTrans: "protocol",
            rowText: "protocol",
            width: "12%"
        }, {
            headerTextTrans: "comment",
            rowText: "comment",
            width: "20%"
        }];

        /**
         * prot_map VM
         * @class PortMapVM
         */
        function PortMapVM() {
            var self = this;
            var info = getPortMap();

            self.portMapEnable = ko.observable(info.portMapEnable);
            self.oriPortMapEnable = ko.observable(info.portMapEnable);

            self.sourcePort = ko.observable('');
            self.destIpAddress = ko.observable('');
            self.destPort = ko.observable('');

            self.modes = ko.observableArray(protocolModes);
            self.selectedMode = ko.observable('TCP&UDP');
            self.comment = ko.observable('');

            self.rules = ko.observableArray(info.portMapRules);

            self.gridTemplate = new ko.simpleGrid.viewModel({
                data: self.rules(),
                idName: "index",
                columns: columnsTmpl,
                tmplType: 'list',
                pageSize: 10
            });

            /**
             * 设定,新增,删除回调函数
             * @method callback
             */
            self.callback = function(result) {
                if (result.result == "success") {
                    clear();
                    init(self);
                    successOverlay();
                } else {
                    errorOverlay();
                }
            };

            /**
             * 情况添加规则输入
             * @method clear
             */
            function clear() {
                self.sourcePort('');
                self.destIpAddress('');
                self.destPort('');
                self.selectedMode('TCP&UDP');
                self.comment('');
            }

            /**
             * 设定端口映射
             * @method enablePortMap
             */
            self.enablePortMap = function() {
                showLoading();
                var params = {};
                params.portMapEnable = self.portMapEnable();
                service.enablePortMap(params, self.callback);
            };

            /**
             * 保存规则
             * @method save
             */
            self.save = function() {
                if (self.rules().length >= config.portForwardMax) {
                    showAlert("rules_max", null, [config.portForwardMax]);
                    return;
                }

                if (self.checkExist()) {
                    showAlert("rule_exist");
                    return;
                }

                showLoading();
                var params = {};
                params.portMapEnable = self.portMapEnable();
                params.sourcePort = self.sourcePort();
                params.destIpAddress = self.destIpAddress();
                params.destPort = self.destPort();
                params.protocol = self.selectedMode();
                params.comment = self.comment();
                service.setPortMap(params, self.callback);
            };

            /**
             * 检查新增规则是否已经存在
             * @method checkExist
             */
            self.checkExist = function() {
                var newRule = {
                    sourcePort: self.sourcePort(),
                    destIpAddress: self.destIpAddress(),
                    destPort: self.destPort(),
                    protocol: transProtocolValue(self.selectedMode())
                };

                var oldRule;
                var rules = self.rules();
                for (var i = 0; i < rules.length; i++) {
                    oldRule = {
                        sourcePort: rules[i].sourcePort,
                        destIpAddress: rules[i].destIpAddress,
                        destPort: rules[i].destPort,
                        protocol: rules[i].protocol
                    };

                    if (_.isEqual(newRule, oldRule)) {
                        return true;
                    }
                }
                return false;
            };

            /**
             * 删除规则
             * @method deleteMapRules
             */
            self.deleteMapRules = function() {
                var ids = self.gridTemplate.selectedIds();
                if (ids.length == 0) {
                    showAlert("no_data_selected");
                    return;
                }

                showConfirm("", "confirm_data_delete", function() {
                    showLoading();
                    var params = {};
                    params.indexs = ids;
                    service.deleteMapRules(params, self.callback);
                });
            };
        }

        /**
         * 获取port map信息
         * @method getPortMap
         */
        function getPortMap() {
            return service.getPortMap();
        }


        /**
         * 初始化port map view model
         * @method init
         */
        function init(viewModel) {
            var vm;
            if (viewModel) {
                vm = viewModel;
                var info = getPortMap();
                vm.portMapEnable(info.portMapEnable);
                vm.oriPortMapEnable(info.portMapEnable);
                vm.rules(info.portMapRules);
                vm.gridTemplate.clearAllChecked();
                vm.gridTemplate.data(info.portMapRules);
                refreshTableHeight();
                renderCheckbox();
                return;
            }

            vm = new PortMapVM();
            var container = $('#container');
            ko.cleanNode(container[0]);
            ko.applyBindings(vm, container[0]);

            fixTableHeight();

            $('#mapBasicForm').validate({
                submitHandler: function() {
                    vm.enablePortMap();
                }
            });

            $('#portMapListForm').validate({
                submitHandler: function() {
                    vm.deleteMapRules();
                }
            });

            $('#portMapForm').validate({
                submitHandler: function() {
                    vm.save();
                },
                rules: {
                    txtDestIpAddress: {
                        ip_check: true
                    },
                    txtSourcePort: {
                        digits: true,
                        range_except: [1, 65000]
                    },
                    txtDestPort: {
                        digits: true,
                        range_except: [1, 65000]
                    },
                    txtComment: {
                        comment_check: true
                    }
                },
                errorPlacement: function(error, element) {
                    if (element.attr("name") == "txtDestIpAddress") {
                        error.appendTo("#txtDestIpAddressErrorDiv");
                    } else if (element.attr("name") == "txtSourcePort") {
                        error.appendTo("#txtSourcePortErrorDiv");
                    } else if (element.attr("name") == "txtDestPort") {
                        error.appendTo("#txtDestPortErrorDiv");
                    } else
                        error.insertAfter(element);
                }
            });
        }

        init();
        $('#innerContainer').translate();
    });
</script>